import { Controller, Post, UseInterceptors, UploadedFile, BadRequestException } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import { extname, join } from 'path';
import { v4 as uuidv4 } from 'uuid';

@Controller('v1/upload')
export class UploadController {
  @Post()
  @UseInterceptors(
    FileInterceptor('file', {
      storage: diskStorage({
        destination: './uploads',
        filename: (req, file, callback) => {
          try {
            const uniqueSuffix = uuidv4();
            callback(null, `${uniqueSuffix}${extname(file.originalname)}`);
          } catch (error) {
            callback(error, null);
          }
        },
      }),
      fileFilter: (req, file, callback) => {
        const allowedMimeTypes = [
          'image/jpeg',
          'image/png',
          'image/gif',
          'image/jpg'
        ];

        if (!allowedMimeTypes.includes(file.mimetype)) {
          return callback(new BadRequestException('只允许上传 JPG/JPEG/PNG/GIF 格式的图片!'), false);
        }
        callback(null, true);
      },
      limits: {
        fileSize: 2 * 1024 * 1024, // 2MB
      },
    }),
  )
  async uploadFile(@UploadedFile() file: Express.Multer.File) {
    if (!file) {
      throw new BadRequestException('文件上传失败');
    }

    return {
      url: `http://localhost:3000/uploads/${file.filename}`,
      originalName: file.originalname,
      size: file.size,
    };
  }
} 